<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/10/9
 * Time: 10:27
 * 收藏
 */
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

class Favorite extends Api {
	
	/**
	 * 收藏列表
	 */
	public function index() {
		$userId = $this->auth->id;
		
		$page = $this->request->post('page', 1, 'intval');
		
		$rows = Db::name('favorite')->alias('f')
			->join('goods g', 'f.goods_id = g.id', 'left')
			->where(['f.status' => 1, 'f.user_id' => $userId, 'g.status' => \app\common\model\Goods::STATUS_SALE])
			->page($page)
			->order(['f.update_time' => 'desc'])
			->field('f.id, f.goods_id, g.name, g.image, g.price')
			->select();
		
		$count = Db::name('favorite')
			->where(['status' => 1, 'user_id' => $userId])
			->count();
		$this->success('查询成功', [
			'list' => $rows,
			'total' => $count,
			'page' => $page
		]);
	}
	
	/**
	 * 添加收藏
	 */
	public function add() {
		$goodsId = $this->request->post('id');
		!$goodsId && $this->error('参数错误');
		
		$userId = $this->auth->id;
		
		$data = [
			'goods_id' => $goodsId,
			'user_id' => $userId
		];
		
		$model = new \app\common\model\Favorite();
		$row = $model->where($data)->find();
		if($row) {
			$status = $row['status'] == 1 ? 0 : 1;
			$res = $model->save([
				'status' => $status,
			], $data);
			$msg = $row['status'] == 1 ? '操作成功' : '收藏成功';
		} else {
			$res = $model->isUpdate(false)
				->save($data);
			
			$msg = '收藏成功';
		}
		
		if($res !== false) {
			$this->success($msg);
		} else {
			$this->error('收藏出错');
		}
	}
	
	
	/**
	 * 删除收藏
	 */
	public function del() {
		$ids = $this->request->post('ids');
		!$ids && $this->error('参数错误');
		
		$userId = $this->auth->id;
		
		$model = new \app\common\model\Favorite();
		
		$res = $model->save(['status' => 0],[
			'user_id' => $userId,
			'id' => ['in', $ids]
		]);
		
		if($res !== false) {
			$this->success('操作成功');
		} else {
			$this->error('操作出错');
		}
	}
}
